<template>
    <el-row :gutter="30">
        <el-card style="margin:0 0 20px 0px">
            <el-row class="form-row">
                <el-form label-position="right" :model="filters" inline>
                    <el-form-item label="合同名称">
                        <div class="filters-input">
                            <el-input v-model="filters.name"></el-input>
                        </div>
                    </el-form-item>
                    <el-form-item label="经办人">
                        <div class="filters-input">
                            <el-input v-model="filters.managerName"></el-input>
                        </div>
                    </el-form-item>
                    <el-form-item label="类别名称">
                        <div class="filters-input">
                            <el-input v-model="filters.categoryName"></el-input>
                        </div>
                    </el-form-item>
                    <el-form-item label="机构简称">
                        <div class="filters-input">
                            <el-input v-model="filters.mechanismAbbreviation"></el-input>
                        </div>
                    </el-form-item>
                    <el-button type="primary" icon="ios-search" size="large" @click="loadData()">
                        搜索
                    </el-button>
                </el-form>
            </el-row>
            <el-row class="form-row">
                <el-button type="primary" icon="md-add" size="large"
                           @click="addContract('新增')">新增
                </el-button>
            </el-row>

            <el-table stripe border v-loading="tableLoading" :data="tableData" size="large" ref="table">
                <template slot="empty">暂无数据</template>
                <el-table-column prop="code" label="合同编号"></el-table-column>
                <el-table-column prop="name" label="合同名称"></el-table-column>
                <el-table-column prop="categoryName" label="合同类别"></el-table-column>
                <el-table-column prop="mechanismAbbreviation" label="机构简称"></el-table-column>
                <el-table-column prop="managerName" label="合同经办人"></el-table-column>
                <el-table-column prop="signTime" :formatter="dateFormatter" label="合同签订日期"></el-table-column>
                <el-table-column prop="validityPeriod" label="合同有效期"></el-table-column>
                <el-table-column label="操作" width="150" align="center">
                    <template slot-scope="scope">
                        <el-dropdown>
                            <el-button type="primary">
                                操作<i class="el-icon-arrow-down el-icon--right"></i>
                            </el-button>
                            <el-dropdown-menu slot="dropdown" align="center">
                                <el-dropdown-item @click.native="getContractInfo(scope.row.id)">合同详情</el-dropdown-item>
                                <el-dropdown-item @click.native="downloadContract(scope.row.textUrl)">下载合同
                                </el-dropdown-item>
                                <el-dropdown-item @click.native="addContract('修改',scope.row)">修改</el-dropdown-item>
                                <el-dropdown-item @click.native="deleteContract(scope.row.id)">删除</el-dropdown-item>
                            </el-dropdown-menu>
                        </el-dropdown>
                    </template>
                </el-table-column>
            </el-table>
            <Page style="margin: 10px 0;" :total="pageTotal" :current="pageNum" :page-size="pageSize" show-total
                  show-sizer show-elevator @on-change="handlePage" @on-page-size-change='handlePageSize'>
            </Page>
        </el-card>
        <!--新增修改-->
        <el-dialog :title="contractTitle" :visible.sync="contractVisible" :close-on-click-modal="false" width="900px">
            <el-form :model="contract" :rules="rules" ref="contractForm" label-width="150px">
                <el-form-item label="合同编号" prop="code">
                    <el-input v-model="contract.code" placeholder="请输入合同编号"></el-input>
                </el-form-item>
                <el-form-item label="合同名称" prop="name">
                    <el-input v-model="contract.name" placeholder="请输入合同名称"></el-input>
                </el-form-item>
                <el-form-item label="合同类别" prop="categoryId">
                    <el-select v-model="contract.categoryId" style="width:100%" clearable placeholder="请选择">
                        <el-option
                            v-for="item in categoryList"
                            :key="item.id"
                            :label="item.categoryName"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="机构名称" prop="mechanismId">
                    <el-select v-model="contract.mechanismId" style="width:100%" clearable placeholder="请选择">
                        <el-option
                            v-for="item in mechanismList"
                            :key="item.id"
                            :label="item.mechanismFullName"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="合同经办人" prop="wyUserId">
                    <el-select style="width: 100%" v-model="contract.wyUserId" @focus="alertMemberDialog" multiple
                               placeholder="请选择">
                        <el-option
                            v-for="item in managerUser"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="合同签订日期" prop="signTime">
                    <el-date-picker v-model="contract.signTime" style="width: 100%" type="date"
                                    placeholder="选择日期"></el-date-picker>
                </el-form-item>
                <el-form-item label="合同有效期" prop="validityPeriod">
                    <el-input v-model="contract.validityPeriod" placeholder="请输入合同有效期"></el-input>
                </el-form-item>
                <el-form-item label="上传合同文本">
                    <el-upload class="upload-demo"
                               accept="application/msword"
                               :headers="{'x-access-token':token}"
                               :limit="1"
                               :on-exceed="uploadExceed"
                               :on-success="uploadSuccess"
                               :on-progress="uploadProgress"
                               :data="path" drag :action="act" :multiple="false">
                        <i class="el-icon-upload"></i>
                        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                    </el-upload>
                    <el-input type="hidden" v-model="contract.textUrl"/>
                </el-form-item>
            </el-form>
            <div slot="footer">
                <el-button @click="contractVisible = false">取 消</el-button>
                <el-button type="primary" :loading="formLoading" @click="sureAddContract('contractForm')">确 定
                </el-button>
            </div>
        </el-dialog>
        <!--人员选择插件-->
        <MemberSelector :data-tree="treeList" mode="MultiMember" :data-member="memberList" ref="memberSelector"
                        @treenodeclick="treeNodeClick" @affirmative="confirmMember">
        </MemberSelector>
    </el-row>
</template>
<script>
    import Treeselect from "@riophae/vue-treeselect";
    import MemberSelector from "../../components/member-selector/selector";
    import moment from "moment"
    import baseURL from '_conf/url'
    import Cookies from 'js-cookie'
    import {TOKEN_KEY} from '@/libs/util'

    const token = Cookies.get(TOKEN_KEY)

    const act = baseURL + "/common/uploadFile"
    export default {
        components: {
            MemberSelector,
            Treeselect
        },
        data() {
            return {
                token:token,
                //校验规则
                rules: {
                    code: [
                        {
                            required: true,
                            message: "请输入合同编号",
                        }
                    ],
                    name: [
                        {
                            required: true,
                            message: "请输入合同名称",
                        }
                    ],
                    categoryId: [
                        {
                            required: true,
                            message: "请选择合同类别",
                        }
                    ],
                    mechanismId: [
                        {
                            required: true,
                            message: "请选择合同机构",
                        }
                    ],
                    wyUserId: [
                        {
                            required: true,
                            message: "请选择合同经办人",
                        }
                    ],
                    signTime: [
                        {
                            required: true,
                            message: "请选择合同签订日期",
                        }
                    ],
                    validityPeriod: [
                        {
                            required: true,
                            message: "请选择合同有效期",
                        }
                    ],
                },
                uploadMes: "请上传合同文本",
                contractTitle: "",
                contractVisible: false,
                contract: {
                    wyUserId: [],
                },
                act: act,
                path: {fileName: "contract/"},
                categoryList: [],
                mechanismList: [],
                //页码
                pageNum: 1,
                //每页数量
                pageSize: 10,
                //总数
                pageTotal: 0,
                filters: {},
                //表单提交状态
                formLoading: false,
                tableLoading: false,
                tableData: [],
                treeList: [],
                memberList: [],
                managerUser: [],
            };
        },

        created: function () {
            this.getCategory();
            this.getMechanismList();
            this.loadData();
            this.getTreeData();
            this.getMemberList();
        },
        methods: {
            //弹出部门人员选择框
            alertMemberDialog: function () {
                this.$refs.memberSelector.showDialog();
            },

            //获取部门信息
            getTreeData() {
                this.postRequest("/api/manageHR/getCompany").then(res => {
                    if (res.code == 20000) {
                        this.treeList = res.data;
                    } else {
                        this.$Message.error({
                            content: res.message,
                            duration: 5
                        });
                    }
                });
            },

            //部门点击选择
            treeNodeClick: function (data) {
                this.getMemberList(data);
            },

            //确认选择人员
            confirmMember(data) {
                this.contract.wyUserId = [];
                this.managerUser = [];
                const _this = this;
                data.forEach(function (c) {
                    const user = {
                        id: (c.id),
                        name: (c.name)
                    };
                    _this.contract.wyUserId.push(c.id);
                    _this.managerUser.push(user)
                });
            },

            //获取成员
            getMemberList(data) {
                const params = {};
                params.pageNum = null;
                if (data) {
                    params.companyId = data.companyId;
                }
                //与后台交换数据
                this.postRequest("/api/manageHR/userLoadData", params).then(res => {
                    if (res.code == 20000) {
                        const _this = this;
                        const tmpList = [];
                        res.data.list.forEach(function (c) {
                            const list = c;
                            list.label = (c.name);
                            tmpList.push(list);
                        });
                        this.memberList = tmpList;
                        this.managerUser = tmpList;
                    } else {
                        this.$Message.error({
                            content: res.message,
                            duration: 5
                        });
                    }
                });
            },

            //加载合同类别
            getCategory() {
                this.getRequest("/api/contractCategory/getCategoryList").then(res => {
                    if (res.code == 20000) {
                        this.categoryList = res.data;
                    } else {
                        this.$message.error(res.message);
                    }
                });
            },

            //加载合同机构
            getMechanismList() {
                this.getRequest("/api/mechanisms/getMechanismList").then(res => {
                    if (res.code == 20000) {
                        this.mechanismList = res.data;
                    } else {
                        this.$message.error(res.message);
                    }
                });
            },

            //加载数据
            loadData() {
                if (this.tableLoading) return;
                this.tableLoading = true;
                let params = this.filters;
                params.pageNum = this.pageNum;
                params.pageSize = this.pageSize;
                //与后台交换数据
                this.postRequest("/api/contract/loadData", params).then(res => {
                    this.tableLoading = false;
                    if (res.code == 20000) {
                        this.tableData = res.data.list;
                        this.pageTotal = res.data.total;
                    } else {
                        this.tableData = [];
                        this.$Message.error({
                            content: res.message,
                            duration: 5
                        });
                    }
                });
            },

            //合同签订日期格式化
            dateFormatter(row, column, cellValue, index) {
                if (typeof cellValue === 'string') {
                    if (cellValue) {
                        return cellValue.substr(0, 10);
                    }
                }
            },

            //打开新增页面
            addContract(str, row) {
                this.contract = {};
                this.contract.wyUserId = [];
                this.contractTitle = str;
                this.contractVisible = true;
                if ('修改' == str) {
                    this.contract = row;
                }
                console.log(this.contract)
            },

            //确定新增
            sureAddContract(contractForm) {
                this.$refs[contractForm].validate((valid) => {
                    if (valid) {
                        if (!this.contract.textUrl) {
                            this.formLoading = false;
                            this.$message.error(this.uploadMes);
                            return false;
                        }
                        this.formLoading = true;
                        this.contract.signTime = moment(this.contract.signTime).format("YYYY-MM-DD");
                        this.postRequest("/api/contract/saveOrUpdateInfo", this.contract).then(res => {
                            this.formLoading = false;
                            if (res.code == 20000) {
                                this.contractVisible = false;
                                this.loadData();
                                this.$Message.success({
                                    content: "操作成功",
                                    duration: 5
                                });
                            } else {
                                this.$message.error(res.message);
                            }
                        });
                    }
                });
            },

            //上传成功
            uploadSuccess(res) {
                console.log(res)
                this.contract.textUrl = res;
                this.uploadMes = "请上传合同文本";
            },

            //上传中
            uploadProgress() {
                this.uploadMes = "请等待合同文本上传完成";
            },

            //只支持上传一个文件，多个提示错误信息
            uploadExceed() {
                this.$message.error("只能上传一个文件");
            },
            //下载合同
            downloadContract(textUrl) {
                if (!textUrl) {
                    this.$message.error("该合同暂未上传，不提供下载");
                } else {
                    window.location.href = textUrl;
                }
            },

            //删除
            deleteContract(id) {
                this.$Modal.confirm({
                    title: "提示",
                    content: "确定删除？",
                    onOk: () => {
                        this.getRequest("/api/contract/deleteContractInfo?id=" + id).then(res => {
                            if (res.code == 20000) {
                                this.loadData();
                                this.$Message.success({
                                    content: "操作成功",
                                    duration: 5
                                });
                            } else {
                                this.$message.error(res.message);
                            }
                        });
                    }
                });
            },

            //查看合同详情
            getContractInfo(id) {
                this.$router.push({path: 'matterAndFunds', query: {id: id}});
                // this.filters.recordId = this.$route.query.recordId;
            },

            handlePage(value) {
                this.pageNum = value;
                this.loadData();
            },
            handlePageSize(value) {
                this.pageSize = value;
                this.loadData();
            },
        }
    };
</script>
